package com.songlanyun.modules.appconfig.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.common.utils.BeanUtil;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.Query;
import com.songlanyun.modules.appconfig.dao.AppConfigDao;
import com.songlanyun.modules.appconfig.entity.AppConfig;
import com.songlanyun.modules.appconfig.service.AppConfigService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 *
 */
@Service
public class AppConfigServiceImpl extends ServiceImpl<AppConfigDao, AppConfig> implements AppConfigService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Integer number = MapUtil.getInt(params, "number");
        IPage<AppConfig> page = this.page(
                new Query<AppConfig>().getPage(params),
                new LambdaQueryWrapper<AppConfig>()
                        .eq(ObjectUtil.isNotNull(number), AppConfig::getNumber, number)
                        .orderByDesc(AppConfig::getNumber)
        );

        return new PageUtils(page);
    }

    @Override
    public AppConfig getOne() {
        return this.baseMapper.selectOne(
                new LambdaQueryWrapper<AppConfig>()
                        .orderByDesc(AppConfig::getNumber)
                        .last("limit 1")
        );
    }

    @Override
    public void add(AppConfig appConfig) {
        AppConfig one = getOne();
        if (one != null) {
            BeanUtil.copyPropertiesIgnoreNull(appConfig, one);
            this.baseMapper.updateById(one);
        } else {
            this.baseMapper.insert(appConfig);
        }
    }

    @Override
    public void saveConfig(AppConfig appConfig) {

        verifyNumber(appConfig);
        this.baseMapper.insert(appConfig);
    }

    @Override
    public void updateConfig(AppConfig appConfig) {
        verifyNumber(appConfig);
        this.baseMapper.updateById(appConfig);
    }

    private void verifyNumber(AppConfig appConfig) {
        Integer count = this.baseMapper.selectCount(
                new LambdaQueryWrapper<AppConfig>()
                        .eq(AppConfig::getNumber, appConfig.getNumber())
                        .ne(appConfig.getId() != null, AppConfig::getId, appConfig.getId())
        );
        if (count > 0) {
            throw new RRException("版本号不能重复");
        }
    }
}
